package com.mical.demo.provider;


import com.mical.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * 登录认证类：扩展 AuthenticationProvider
 * @author pan_junbiao
 **/
@Component
public class CustomAuthenticationProvider  implements AuthenticationProvider
{
    @Autowired
    private UserService userervice;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException
    {
        //从 Authentication 对象中获取用户名称和身份凭证信息
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        UserDetails user = userervice.loadUserByUsername(username);

        if (user!=null && passwordEncoder.matches(password, user.getPassword()))
        {
            //密码匹配成功，则构建一个 UsernamePasswordAuthenticationToken 对象并返回
            return new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), user.getAuthorities());
        } else
        {
            //密码匹配失败，则抛出异常
            throw new BadCredentialsException("用户密码不正确");
        }
    }

    @Override
    public boolean supports(Class<?> authenticationType)
    {
        return authenticationType.equals(UsernamePasswordAuthenticationToken.class);
    }
}